package com.budwk.app.sso.controllers;


import cn.dev33.satoken.sso.SaSsoProcessor;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaFoxUtil;
import cn.dev33.satoken.util.SaResult;
import com.budwk.app.sys.services.SysUnitService;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.uc.services.AuthService;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.log.annotation.SLog;
import com.budwk.starter.log.enums.LogType;
import lombok.extern.slf4j.Slf4j;

import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.ioc.loader.annotation.Value;

import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;



/**
 * 接入蓝信统一登录认证
 * 校验票据
 */
@IocBean
@At("/ssoiam")
@Slf4j
@SLog(tag = "用户登录IAM")
public class SsoIamController {

    /**
     * 业务系统访问地址
     */
    @Value(name = "cusconfig.ssoiam.serverUrl")
    private String serverUrl;

    /**
     * IAM CAS 地址前缀
     */
    @Value(name = "cusconfig.ssoiam.casUrlPrefix")
    private String casUrlPrefix;

    /**
     * 门户统一登录平台地址
     */
    @Value(name = "cusconfig.sso.serverUrl")
    private String ssoUrlPrefix;
    @Inject
    SysUserService sysUserService;

    @Inject
    AuthService authService;
    @Inject
    private SysUnitService sysUnitService;

    //当前是否登录
    @At("/isLogin")
    @Ok("json")
    @SLog(type = LogType.LOGIN ,value = "IAM校验用户登录状态")
    public Object isLogin() {
        System.out.println("登录状态："+StpUtil.isLogin());
        return Result.data(StpUtil.isLogin());
    }

    // 返回蓝政SSO认证中心登录地址
    @At("/getSsoAuthUrl")
    @Ok("json")
    public Result getSsoAuthUrl(@Param("clientLoginUrl") String clientLoginUrl) {
        String serverAuthUrl = casUrlPrefix+"/login";
        // 对back地址编码
        String back = "";
        back = (back == null ? "" : back);
        back = SaFoxUtil.encodeUrl(back);
        /*
         * 部分 Servlet 版本 request.getRequestURL() 返回的 url 带有 query 参数，形如：http://domain.com?id=1，
         * 如果不加判断会造成最终生成的 serverAuthUrl 带有双 back 参数 ，这个 if 判断正是为了解决此问题
         */
        if( ! clientLoginUrl.contains("back" + "=" + back) ) {
            clientLoginUrl = SaFoxUtil.joinParam(clientLoginUrl, "back", back);
        }
        // 返回
        serverAuthUrl =  SaFoxUtil.joinParam(serverAuthUrl, "service", clientLoginUrl);
        return Result.data(serverAuthUrl);
    }

    // 根据ticket进行登录
    @At("/doLoginByTicket")
    @Ok("json")
    @SLog(type = LogType.LOGIN ,value = "IAM校验用户票据:")
    public Result doLoginByTicket(@Param("ticket")String ticket) {
        String serverAuthUrl = ssoUrlPrefix +"/ssoiam/doLoginByTicket";
        // 返回
        serverAuthUrl =  SaFoxUtil.joinParam(serverAuthUrl, "ticket", ticket);
        return Result.data(serverAuthUrl);
    }

    //客户端sso-client
    @At("/login")
    @Ok("re")
    public Object login(){
        System.out.println("客户端登录");
        Object object = SaSsoProcessor.instance.ssoLogin();
        if (object == null) {
            object = "";
        }
        return object;
    }

    //单点注销地址
    @At("/logout")
    @Ok("raw")
    public Object logout(){
        System.out.println("客户端单点注销");
        System.out.println("客户端登录状态：" + StpUtil.isLogin());
        Object object = SaSsoProcessor.instance.ssoLogout();
        if (object == null) {
            object = "";
        }
        if (object instanceof SaResult) {
            SaResult saResult = (SaResult) object;
            if (saResult.getCode() == SaResult.CODE_SUCCESS) {
                saResult.setCode(0);
                object = saResult;
            }
        }
        return object;
    }

    //单点注销回调
    @At("/logoutCall")
    @Ok("json")
    public Object logoutCall(){
        System.out.println("客户端单点注销回调");
        return SaSsoProcessor.instance.ssoLogoutCall();
    }


}
